package com.archermind.style.service;

import com.archermind.style.bean.OperationLog;
import com.archermind.style.bean.User;
import com.feng.fengDUtil.BaseService;
import com.archermind.style.util.Search;
import com.archermind.style.util.SessionUtil;
import com.feng.fengDUtil.Page;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;


@Service
@Transactional
public class OperationService  extends BaseService {

    private static final Logger log = LoggerFactory.getLogger(OperationService.class);

    public Page query(Page page, Search search) {
        ArrayList params = new ArrayList();
        String sql = "select u.*," +
                "(select s.name From instance s where s.id = u.instanceId limit 1) as instanceName," +
                "(select s.name From user s where s.id = u.op limit 1) as opName " +
                " from operation_log u where 1=1 ";
        if(StringUtils.isNotEmpty(search.getName())){
            sql+=" and exists (select 1 from instance s where s.id = u.instanceId and s.name like ? )";
            params.add(processLike(search.getName()));
        }
        sql+=" order by id desc";
        findPageList(Map.class,sql,page,params.toArray());
        return page;
    }

    public void saveLog(String comment){
        try {
            saveLog(comment,null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void saveLog(String comment,Integer instanceId) throws Exception{
        User user = SessionUtil.getCurUser();
        if(user.getId()!=1 && instanceId!=null){
            String instanceIds = user.getWriteInstanceIds()==null?"":user.getWriteInstanceIds();
           boolean isContain = Arrays.asList(instanceIds.split(",")).contains(instanceId.toString());
           if(!isContain){
               throw new Exception("样式版本id："+instanceId+"不在可编辑范围内！");
           }
        }
        OperationLog opLog = new OperationLog();
        opLog.setInstanceId(instanceId);
        opLog.setComment(comment);
        opLog.setOp(SessionUtil.getCurUserId());
        opLog.setOptime(new Date());
        insert(opLog);
    }

}
